package org.langqiao.thread;

public class MultiThread {
	private static int num = 0;
	
	/**
	 * 一个对象有一把锁，关键字synchronized取得锁都是对象锁， 而不是把一段代码（方法）当做锁，
	 * 代码块声明为synchronized，有两个重要后果，原子性和可见性
	 * 示例代码中那个线程执行synchronized关键字方法，那个线程就持有该方法所属对象的锁(lock),两个对象，线程就获取2个不同的锁，他们互不影响
	 * 有一种情况是相同的锁，即在静态方法上加上synchronized关键字，表示锁定.class类，类一级别的锁(独占.class类)
	 * @param tag
	 */
	public static synchronized void printNum(String tag){
		try {
			if(tag.equals("a")){
				num = 100;
				System.out.println("tag a set num over");
				Thread.sleep(1000);
			}else{
				num = 200;
				System.out.println("tag b set num over");
			}
			
			System.out.println("tag="+tag+",num="+num);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) {
		final MultiThread m1 = new MultiThread();
		final MultiThread m2 = new MultiThread();
		
		Thread t1 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				m1.printNum("a");
			}
		});
		
		Thread t2 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				m2.printNum("b");
			}
		});
		t1.start();
		t2.start();
	}
}
